package com.zhiban.project.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import dinamica.GenericOutput;
import dinamica.GenericTransaction;

/**
 * 下载题目模版
 * 
 * @author lxp
 *
 */
public class DownloadQuestionTemplate extends GenericOutput {

	public DownloadQuestionTemplate() {
	}

	public void print(GenericTransaction data) throws Throwable {
		try {
			String value = this.getRequest().getParameter("value");
			String templatepath = this.getRequest().getRealPath("/")
					+ File.separator + "template";
			if (value == null) {
				return;
			}
			String ext = FilenameUtils.getExtension(value);
			File templateFile = new File(templatepath, value);
			getResponse().setContentType("application/" + ext);
			getResponse().setHeader("Content-Disposition",
					getAttachmentString(value));
			ServletOutputStream out = getResponse().getOutputStream();
			FileUtils.copyFile(templateFile, out);
			out.close();
		} catch (Throwable e) {
			throw new Throwable("操作失败", e);
		}
	}

	protected String getAttachmentString(String excelFileName) {
		String filename = excelFileName;
		try {
			if (getRequest().getHeader("user-agent").indexOf("MSIE") != -1) {
				filename = URLEncoder.encode(filename, "utf-8");
				filename = filename.replaceAll("\\+", "%20");
			} else {
				filename = new String(filename.getBytes("utf-8"), "iso-8859-1");
			}
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return (new StringBuilder("attachment; filename=\"")).append(filename)
				.append("\";").toString();
	}
}